package cn.itcast.goods.category.web.servlet;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import cn.itcast.commons.CommonUtils;
import cn.itcast.goods.category.doamin.Category;
import cn.itcast.jdbc.TxQueryRunner;

public class CategoryDaoA {
	QueryRunner qr=new TxQueryRunner();
	public List<Category> findAll() throws Exception{
		String sql="select * from t_category where pid is null";
		List<Map<String, Object>>mapList=qr.query(sql, new MapListHandler());
		List<Category> parents=toCategoryList(mapList);
		for(Category parent:parents){
			parent.setChildren(getByPid(parent.getCid()));
		}
		
		return parents;
	}
	
	private List<Category> getByPid(String pid) throws SQLException {
		String sql="select * from t_category where pid=?";
		List<Map<String, Object>>mapList=qr.query(sql, new MapListHandler(),pid);
		return toCategoryList(mapList);
	}
	
	private List<Category> toCategoryList(List<Map<String, Object>> mapList) {
		List<Category> list=new ArrayList<Category>();
		for(Map<String, Object> map:mapList){
			list.add(toCategory(map));
		}
		return list;
		
	}
	private Category toCategory(Map<String, Object> map){
		Category category=CommonUtils.toBean(map, Category.class);
		String pid=(String)map.get("pid");
		if(pid!=null){
			Category parent=new Category();
			parent.setCid(pid);
			category.setParent(parent);
		}
		return category;
	}
}
